package com.xiyu.service.repository.mailbox.mail;

import com.xiyu.service.model.mailbox.mail.MailboxMailLabel;
import com.xiyu.service.model.mailbox.mail.MailboxMailLabelTable;
import org.babyfish.jimmer.spring.repository.JRepository;

import java.util.Optional;
import java.util.List;

public interface MailboxMailLabelRepository extends JRepository<MailboxMailLabel, Long> {
    MailboxMailLabelTable mailboxMailLabelTable = MailboxMailLabelTable.$;

    default void deleteByLabelFolderId(Long labelFolderId){
        sql().createDelete(mailboxMailLabelTable)
                .where(mailboxMailLabelTable.labelFolderId().eq(labelFolderId))
                .execute();
    }

    default Long getAccountLabelMailCount(Long accountId){
        return sql().createQuery(mailboxMailLabelTable)
                .where(mailboxMailLabelTable.mail().accountId().eq(accountId))
                .groupBy(mailboxMailLabelTable.mail().accountId())
                .select(mailboxMailLabelTable.mailId().count(true)).fetchOptional().orElse(0L);
    }

    default Long getAccountLabelUnreadMailCount(Long accountId){
        return sql().createQuery(mailboxMailLabelTable)
                .where(mailboxMailLabelTable.mail().accountId().eq(accountId))
                .where(mailboxMailLabelTable.mail().isRead().eq(true))
                .groupBy(mailboxMailLabelTable.mail().accountId())
                .select(mailboxMailLabelTable.mailId().count(true)).fetchOptional().orElse(0L);
    }

    Optional<MailboxMailLabel> findByMailIdAndLabelFolderId(Long mailId, Long labelFolderId);

    List<MailboxMailLabel> findByMailId(Long mailId);

}